package myself.a002StackAndQueue;

import java.util.LinkedList;
import java.util.Queue;

/**
 * @author 叶之越
 * Description
 * Date 2021/1/21
 * Time 22:17
 * Mail 739153436@qq.com
 */
public class TwoQueuesImplementStack {
    private Queue<Integer> q1 = new LinkedList<>();
    private Queue<Integer> q2 = new LinkedList<>();

    public static void main(String[] args) throws Exception {
        TwoQueuesImplementStack stack = new TwoQueuesImplementStack();

        stack.push(1);
        stack.push(2);
        stack.push(3);
        stack.pop();

        while (!stack.isEmpty()) {
            System.out.println(stack.pop());
        }
    }

    public void push(int ele) {
        if (isEmpty()) {
            q1.add(ele);
            return;
        }
        if (q1.isEmpty()) {
            q2.add(ele);
        } else {
            q1.add(ele);
        }
    }

    public Integer pop() throws Exception {
        if (isEmpty()) {
            throw new Exception();
        }

        if (q1.isEmpty()) {
            while (q2.size() > 1) {
                q1.add(q2.poll());
            }
            return q2.poll();
        }

        while (q1.size() > 1) {
            q2.add(q1.poll());
        }
        return q1.poll();
    }

    public boolean isEmpty() {
        return q1.isEmpty() && q2.isEmpty();
    }
}
